<template>
  <BasicDrawer v-bind="$attrs" @register="registerModal" showFooter @ok="handleSubmit">
    <BasicTree treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" ref="treeRef" title="接口授权" search checkable
      checkStrictly :defaultExpandAll="true" :treeData="treeData" :fieldNames="{ key: 'id', title: 'apiName' }"
      :value="mid" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { onMounted, ref, unref } from 'vue';
import { BasicTree, TreeActionType } from '/@/components/Tree';
import { getApiTree } from '/@/api/system/api';
import { setAdminApi } from '/@/api/system/admin';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

const emit = defineEmits(['success', 'register'])
const treeRef = ref<Nullable<TreeActionType>>(null);
const treeData = ref<any[]>([]);
const oid = ref(0);
const mid = ref([]);

onMounted(async () => {
  await fetch();
})

async function fetch() {
  treeData.value = (await getApiTree()) as any;
}


function getTree() {
  const tree = unref(treeRef);
  if (!tree) {
    throw new Error('tree is null!');
  }
  return tree;
}

const [registerModal, { setDrawerProps, closeDrawer }] = useDrawerInner(async ({ record }) => {
  setDrawerProps({ confirmLoading: false });
  oid.value = record.id;
  mid.value = record.apis;
});

async function handleSubmit() {
  try {
    setDrawerProps({ confirmLoading: true });
    const keys = getTree().getCheckedKeys() as any;
    await setAdminApi({ oid: oid.value, mid: keys.checked });
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
